import { useState } from 'react';
import { Card, Text, Group, Stack, Button, rem } from '@mantine/core';
import { Dropzone, FileWithPath } from '@mantine/dropzone';
import { IconUpload, IconPhoto, IconX } from '@tabler/icons-react';
import axios from 'axios';
import { IconPlant2, IconFileDescription, IconBulb } from '@tabler/icons-react';

interface RecognizeResult {
    name: string;
    description: string;
    solution: string;
}

const PlantRecognize = () => {
    const [files, setFiles] = useState<FileWithPath[]>([]);
    const [loading, setLoading] = useState(false);
    const [result, setResult] = useState<RecognizeResult | null>(null);
    const [errorMsg, setErrorMsg] = useState<string | null>(null);

    const handleDrop = (files: FileWithPath[]) => {
        setFiles(files);
        setResult(null);
        setErrorMsg(null); // 清除之前的错误信息
    };

    const handleRecognize = async () => {
        if (files.length === 0) return;

        setLoading(true);
        setErrorMsg(null); // 每次识别前清除错误信息
        try {
            const formData = new FormData();
            formData.append('file', files[0]);

            const response = await axios.post('/app-api/rec', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });

            console.log("response.data", response.data);

            if (response.data.error && response.data.error === '无法识别') {
                setErrorMsg('未能识别出植物病虫害，请尝试上传更清晰的图片或更换图片。');
                setResult(null);
                setLoading(false);
                return;
            }

            setResult({
                name: response.data.diseases[0].cn_name,
                description: response.data.diseases[0].description,
                solution: response.data.diseases[0].suggestion
            });
        } catch (error) {
            console.error('Recognition failed:', error);
            setErrorMsg('识别过程中出现异常，请稍后重试。');
        } finally {
            setLoading(false);
        }
    };

    const previews = files.map((file, index) => {
        const imageUrl = URL.createObjectURL(file);
        return (
            <Card key={index} padding="sm" radius="md" withBorder>
                <Card.Section>
                    <img
                        src={imageUrl}
                        onLoad={() => URL.revokeObjectURL(imageUrl)}
                        alt={`Upload preview ${index + 1}`}
                        style={{ width: '100%', height: 'auto', maxHeight: '300px', objectFit: 'contain' }}
                    />
                </Card.Section>
            </Card>
        );
    });

    return (
        <Stack gap="lg" p="md">
            <Dropzone
                onDrop={handleDrop}
                accept={['image/png', 'image/jpeg', 'image/jpg', 'image/webp']}
                maxSize={5 * 1024 * 1024}
                styles={{
                    root: {
                        border: '2px dashed var(--mantine-color-gray-4)',
                        backgroundColor: 'var(--mantine-color-gray-0)',
                        borderRadius: 'var(--mantine-radius-md)',
                        transition: 'all 0.2s ease',
                        '&:hover': {
                            backgroundColor: 'var(--mantine-color-gray-1)',
                            borderColor: 'var(--mantine-color-blue-6)'
                        }
                    }
                }}
            >
                <Group gap="xl" justify="center" style={{ minHeight: rem(220), pointerEvents: 'none' }}>
                    <Stack align="center" gap="xs">
                        <Dropzone.Accept>
                            <IconUpload
                                size="3.2rem"
                                stroke={1.5}
                                color="var(--mantine-color-blue-6)"
                            />
                        </Dropzone.Accept>
                        <Dropzone.Reject>
                            <IconX
                                size="3.2rem"
                                stroke={1.5}
                                color="var(--mantine-color-red-6)"
                            />
                        </Dropzone.Reject>
                        <Dropzone.Idle>
                            <IconPhoto size="3.2rem" stroke={1.5} />
                        </Dropzone.Idle>
                        <div style={{ textAlign: 'center' }}>
                            <Text size="xl" inline>
                                拖拽图片到此处或点击上传
                            </Text>
                            <Text size="sm" color="dimmed" inline mt={7} style={{ display: 'block' }}>
                                支持PNG、JPEG格式图片，文件大小不超过5MB
                            </Text>
                        </div>
                    </Stack>
                </Group>
            </Dropzone>

            {previews.length > 0 && (
                <Stack gap="md">
                    {previews}
                    <Button
                        onClick={handleRecognize}
                        loading={loading}
                        size="lg"
                        variant="filled"
                        color="green"
                    >
                        开始识别
                    </Button>
                </Stack>
            )}

            {result && (
                <Card padding="xl" radius="md" withBorder shadow="sm">
                    <Stack gap="lg">
                        <Group>
                            <div
                                style={{
                                    width: '4px',
                                    height: '24px',
                                    backgroundColor: 'var(--mantine-color-green-6)',
                                    borderRadius: '2px'
                                }}
                            />
                            <Text size="xl" fw={600} c="green.7">
                                识别结果
                            </Text>
                        </Group>
                        <Stack gap="md">
                            <Card withBorder shadow="xs" padding="md">
                                <Group gap="xs">
                                    <IconPlant2 size={20} style={{ color: 'var(--mantine-color-green-6)' }} />
                                    <Text fw={500} c="gray.7">病虫害名称</Text>
                                </Group>
                                <Text size="lg" mt="xs">{result.name}</Text>
                            </Card>

                            <Card withBorder shadow="xs" padding="md">
                                <Group gap="xs">
                                    <IconFileDescription size={20} style={{ color: 'var(--mantine-color-blue-6)' }} />
                                    <Text fw={500} c="gray.7">详细描述</Text>
                                </Group>
                                <Text size="lg" mt="xs" style={{ whiteSpace: 'pre-wrap' }}>{result.description}</Text>
                            </Card>

                            <Card withBorder shadow="xs" padding="md">
                                <Group gap="xs">
                                    <IconBulb size={20} style={{ color: 'var(--mantine-color-yellow-6)' }} />
                                    <Text fw={500} c="gray.7">防治建议</Text>
                                </Group>
                                <Text size="lg" mt="xs" style={{ whiteSpace: 'pre-wrap' }}>{result.solution}</Text>
                            </Card>
                        </Stack>
                    </Stack>
                </Card>
            )}
            {errorMsg && (
                <Card withBorder shadow="xs" padding="md" style={{ backgroundColor: '#fffbe6', borderColor: '#ffe58f' }}>
                    <Text color="orange" size="md">{errorMsg}</Text>
                </Card>
            )}
        </Stack>
    );
};

export default PlantRecognize;